<template>
  <el-table :data="userList" border stripe>
    <el-table-column type="index" label="#" />
    <el-table-column label="姓名" prop="username" />
    <el-table-column label="邮箱" prop="email" />
    <el-table-column label="电话" prop="mobile" />
    <el-table-column label="角色" prop="role_name" />
    <el-table-column label="状态">
      <!-- scope里有scope.row这一行对应的信息 -->
      <template slot-scope="scope">
        <el-switch
          v-model="scope.row.mg_state"
          @change="userStateChanged(scope.row)"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180">
      <template slot-scope="scope">
        <!-- 修改 -->
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="showEditDialog(scope.row.id)"
        />
        <!-- 删除 -->
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="removeUserById(scope.row.id)"
        />
        <!-- 分配角色 -->
        <el-tooltip
          effect="dark"
          content="分配角色"
          placement="top"
          :enterable="false"
        >
          <el-button
            type="warning"
            icon="el-icon-setting"
            size="mini"
            @click="setRole(scope.row)"
          />
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { updateUserInfo, removeUserInfo } from 'network/user.js'
export default {
  name: 'UserListArea',
  props: {
    userList: {
      type: Array,
      default() {
        return []
      },
    },
  },
  methods: {
    async userStateChanged(userInfo) {
      const res = await updateUserInfo(userInfo.id, userInfo.mg_state)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    showEditDialog(id) {
      this.$bus.$emit('showEditDialog', id)
    },
    async removeUserById(id) {
      // 弹框询问是否删除数据 取消的话必须用catch捕捉
      // 成功返回confirm 失败返回cancel
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }
      const res = await removeUserInfo(id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败!')
      }
      this.$message.success('删除用户成功')
      this.$bus.$emit('getUserList')
    },
    setRole(userInfo) {
      this.$emit('setRole', userInfo)
    },
  },
}
</script>

<style lang="less" scoped>
</style>